import { FieldItem } from "./components/field-item"
import {MappingField} from "@/components/IndexMapping/types";
import {Button, Card} from 'tdesign-vue-next';
import {AddIcon} from 'tdesign-icons-vue-next';

interface FieldListProps {
  fields: MappingField[]
  setFields: (fields: MappingField[]) => void
}

export function FieldList({ fields, setFields }: FieldListProps) {
  const addField = () => {
    const newField: MappingField = {
      id: `field-${Date.now()}`,
      name: "",
      type: "text",
      index: true,
    }
    setFields([...fields, newField])
  }

  const updateField = (id: string, updates: Partial<MappingField>) => {
    setFields(fields.map((field) => (field.id === id ? { ...field, ...updates } : field)))
  }

  const deleteField = (id: string) => {
    setFields(fields.filter((field) => field.id !== id))
  }

  return (
    <div class="space-y-4">
      {fields.length === 0 ? (
        <Card>
          <div class="py-12 text-center">
            <p class="text-muted-foreground mb-4">还没有添加字段，点击下方按钮添加第一个字段</p>
            <Button onClick={addField}>
              <AddIcon />
              添加字段
            </Button>
          </div>
        </Card>
      ) : (
        <>
          {fields.map((field) => (
            <FieldItem key={field.id} field={field} onUpdate={updateField} onDelete={deleteField} />
          ))}
          <Button variant="outline" onClick={addField} class="w-full bg-transparent">
            <AddIcon />
            添加字段
          </Button>
        </>
      )}
    </div>
  )
}
